package com.jeequan.jeepay.mch.controller;

import com.jeequan.jeepay.core.utils.GoogleAuthenticator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * 项目启动类
 *
 * @Author Asurplus
 */
@Api(tags = "谷歌验证码接口")
@RestController
@RequestMapping("/api/google")
public class GoogleAuthenticatorController {

    /**
     * 生成 Google 密钥，两种方式任选一种
     */
    @ApiOperation("生成 Google 密钥，两种方式任选一种")
    @GetMapping("/getSecret")
    public String getSecret() {
        return GoogleAuthenticator.getSecretKey();
    }

    /**
     * 生成二维码，APP直接扫描绑定，两种方式任选一种
     */
    @ApiOperation("生成二维码")
    @GetMapping("/getQrcode")
    public void getQrcode(String name, HttpServletResponse response) throws Exception {
        // 生成二维码内容
        String qrCodeText = GoogleAuthenticator.getQrCodeText(GoogleAuthenticator.getSecretKey(), name, "");
        // 生成二维码输出
        new SimpleQrcodeGenerator().generate(qrCodeText).toStream(response.getOutputStream());
    }

    /**
     * 获取code
     */
    @ApiOperation("获取code")
    @GetMapping("/getCode")
    public String getCode(String secretKey) {
        return GoogleAuthenticator.getCode(secretKey);
    }

    /**
     * 验证 code 是否正确
     */
    @ApiOperation("验证 code")
    @GetMapping("/checkCode")
    public String checkCode(String secret, String code) {
        boolean b = GoogleAuthenticator.checkCode(secret, Long.parseLong(code), System.currentTimeMillis());
        if (b) {
            return "success";
        }
        return "error";
    }
}